package com.wxt.asmplugins

import org.gradle.api.Project
import org.objectweb.asm.ClassVisitor
import org.objectweb.asm.MethodVisitor
import org.objectweb.asm.Opcodes

/**
 * Created by wanglei on 2017/4/5.
 */
public class OnClickInjector extends ClassVisitor implements Opcodes {
    private final Project project
    private final String path

    OnClickInjector(ClassVisitor classVisitor, Project project, String path) {
        super(Opcodes.ASM5, classVisitor)
        this.project = project
        this.path = path
    }

    @Override
    MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) {
        Utils.log("OnClickInjector visitMethod :access  ${access}"
        + "name {$name} desc {$desc} signature {$signature}")
        MethodVisitor mv = cv.visitMethod(access, name, desc, signature, exceptions);
        MethodVisitor wrappedMv = mv;
        if (mv != null) {
            if (name.equals("onClick") && desc.equals("(Landroid/view/View;)V")) {
                Utils.log("Inject onClick start : ${path}")
                wrappedMv.visitCode()
                mv.visitVarInsn(ALOAD, 1);
                mv.visitMethodInsn(INVOKESTATIC, "com/wxt/asmtest/Test", "onViewClick", "(Landroid/view/View;)V", false);
                Utils.log("Inject OnViewClickListener code in OnClickInjector : ${path}")
            } else if (name.equals("onClick") && desc.equals("(Landroid/content/DialogInterface;I)V")) {
                wrappedMv.visitCode()
                mv.visitVarInsn(ALOAD, 1);
                mv.visitVarInsn(ILOAD, 2);
                mv.visitMethodInsn(INVOKESTATIC, "com/wxt/asmtest/Test", "onDialogClick", "(Landroid/content/DialogInterface;I)V", false);
                Utils.log("Inject OnDialogClickListener code  in OnClickInjector : ${path}")
            } else if (name.equals("onItemClick") && desc.equals("(Landroid/widget/AdapterView;Landroid/view/View;IJ)V")) {
                wrappedMv.visitCode()
                mv.visitVarInsn(ALOAD, 1);
                mv.visitVarInsn(ALOAD, 2);
                mv.visitVarInsn(ILOAD, 3);
                mv.visitVarInsn(LLOAD, 4);
                mv.visitMethodInsn(INVOKESTATIC, "com/wxt/asmtest/Test", "onItemClick", "(Landroid/widget/AdapterView;Landroid/view/View;IJ)V", false);
                Utils.log("Inject OnItemClickListener code : ${path}")
            }
        }
        return wrappedMv;
    }
}
